import random,re
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5.QtGui import QRegExpValidator, QShowEvent, QIcon
from datetime import datetime, timedelta
from utils.threads import InfoThread, RenewThread, FreshInfoThread, UpdateThread
from utils.tools import keyword, read_json, add_json, zrcf, cmc_content, zyhz_fill_word
from utils.tools import drug_bought_by_patient, nutritional_evaluation,dio_report, print_file
from utils.tools import update_patient_info_in, update_patient_info_out, update_patient_info, gen_admisson_card, update_patient_info_id
from utils import tools
import pyautogui, pyperclip

class PatientInfoDialog(QtWidgets.QDialog):
    def __init__(self, patient_info, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.patient_info = patient_info
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("请输入信息")
        self.resize(400, 300)
        layout = QtWidgets.QVBoxLayout()
        btn_layout = QtWidgets.QHBoxLayout()
        btn_layout.addStretch()
        submit_btn = QtWidgets.QPushButton("确定")
        submit_btn.clicked.connect(self.accept)
        self.accepted.connect(self.submit)
        btn_layout.addWidget(submit_btn)

        cancel_btn = QtWidgets.QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        self.rejected.connect(self.cancel)
        btn_layout.addWidget(cancel_btn)

        layout.addLayout(btn_layout)
        # 地址
        layout.addWidget(QtWidgets.QLabel("现住址："))
        self.addr_LE = QtWidgets.QLineEdit()
        addr = self.patient_info.get("addr")
        if addr:
            self.addr_LE.setText(addr)
        
        self.addr_LE.setClearButtonEnabled(True)
        self.addr_LE.setPlaceholderText("请输入现住址")
        layout.addWidget(self.addr_LE)

        # 身份证号码
        layout.addWidget(QtWidgets.QLabel("身份证号码："))
        self.id_no_LE = QtWidgets.QLineEdit()
        id_no = self.patient_info.get("id_no")
        if id_no:
            self.id_no_LE.setText(id_no)
        reg = QtCore.QRegExp('[0-9xX未提供无]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        self.id_no_LE.setValidator(validator)
        self.id_no_LE.setClearButtonEnabled(True)
        layout.addWidget(self.id_no_LE)

        # 联系人姓名
        layout.addWidget(QtWidgets.QLabel("联系人姓名："))
        self.contact_person_LE = QtWidgets.QLineEdit()
        contact_person = self.patient_info.get("contact_person")
        if contact_person:
            self.contact_person_LE.setText(contact_person)
        self.contact_person_LE.setPlaceholderText("请输入联系人姓名")
        self.contact_person_LE.setClearButtonEnabled(True)
        layout.addWidget(self.contact_person_LE)

        # 联系人关系
        layout.addWidget(QtWidgets.QLabel("联系人姓名："))
        self.relationship_LE = QtWidgets.QLineEdit()
        relationship = self.patient_info.get("relationship")
        if relationship:
            self.relationship_LE.setText(relationship)
        else:
            self.relationship_LE.setText("父母")
        self.relationship_LE.setClearButtonEnabled(True)
        layout.addWidget(self.relationship_LE)

        # 电话
        layout.addWidget(QtWidgets.QLabel("电话："))
        self.phone_LE = QtWidgets.QLineEdit()
        phone = self.patient_info.get("phone")
        if phone:
            self.phone_LE.setText(phone)

        reg = QtCore.QRegExp('[0-9]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        self.phone_LE.setValidator(validator)
        self.phone_LE.setPlaceholderText("请输入电话")
        self.phone_LE.setClearButtonEnabled(True)
        self.phone_LE.returnPressed.connect(self.submit)
        layout.addWidget(self.phone_LE)

        self.setLayout(layout)

    def submit(self):
        addr = self.addr_LE.text()
        id_no = self.id_no_LE.text()
        contact_person = self.contact_person_LE.text()
        relationship = self.relationship_LE.text()
        phone = self.phone_LE.text()
        if not (addr and id_no and contact_person and relationship and phone):
            QtWidgets.QMessageBox.critical(self, "错误！", "输入不能为空！")
        else:
            result = addr, id_no, contact_person, relationship, phone
            result = dict(zip(['addr', 'id_no', 'contact_person', 'relationship', 'phone'], result))

            add_json("patient_info.json", result)

            # 窗口最小化
            self.setWindowState(QtCore.Qt.WindowMinimized)
            # pyautogui.PAUSE = 0.5
            info_map = {
                "ward": "儿童消化心血管科",
                "province": "河南省",
                "city": "南阳市",
                "work": "其他",
                "marriage": "未婚",
                "nation": "汉族",
                "null": "无",
                "condition": "一般",
                "relationship": "父母",
                "teller": "患者家属",
                "contact_person": "",
                "addr": "",
                "id_no": "",
                "phone": "",
                "c": "c",
                "v1": "v1",
                "v2": "v2",
                "blank": ''
            }
            info_map.update(result)
            info_list = [
                'ward', 'blank', 'province', 'city', 'work', 'marriage', 'nation',
                'province', 'city', 'null', 'null', 'addr', 'id_no', 'contact_person',
                'condition', 'relationship', 'c', 'phone', 'v1', 'addr', 'teller',
                'null', 'v2'
            ]

            pyautogui.click(1749, 200)
            for i in info_list:
                if i == 'c':
                    pyautogui.hotkey('ctrl', 'a')
                    pyautogui.hotkey('ctrl', 'c')
                    

                    date1 = pyperclip.paste()

                    date1 = datetime.strptime(date1, '%Y.%m.%d %H:%M')
                    date2 = date1 + timedelta(minutes=31)
                    date3 = date1 + timedelta(minutes=56)
                    date2 = datetime.strftime(date2, '%Y.%m.%d %H:%M')
                    date3 = datetime.strftime(date3, '%Y.%m.%d %H:%M')

                elif i == 'v1':
                    pyperclip.copy(date2)
                    pyautogui.hotkey('ctrl', 'v')

                elif i == 'v2':
                    pyperclip.copy(date3)
                    pyautogui.hotkey('ctrl', 'v')
                elif not info_map[i]:
                    pass
                else:
                    pyperclip.copy(info_map[i])
                    pyautogui.hotkey('ctrl', 'v')
                pyautogui.press('tab')

    def cancel(self):
        pass
    def showEvent(self, a0: QShowEvent) -> None:
        self.addr_LE.selectAll()
        self.addr_LE.setFocus()
        return super().showEvent(a0)
class HydDialog(QtWidgets.QDialog):
    # 手写化验单tab
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("")
        # self.resize(500, 400)
        layout = QtWidgets.QVBoxLayout()
        btn_layout = QtWidgets.QHBoxLayout()

        # self.read_clipboard = QtWidgets.QPushButton("读取剪贴板")
        # self.read_clipboard.clicked.connect(self.read_clipboard_func)
        # btn_layout.addWidget(self.read_clipboard)

       
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        # 添加
        self.pushButton = QtWidgets.QPushButton("添加新项目", self)
        self.pushButton.clicked.connect(self.add)
        self.horizontalLayout.addWidget(self.pushButton)
        # 确定按钮
        # self.pushButton_2 = QtWidgets.QPushButton("确定", self)
        # self.pushButton_2.clicked.connect(self.submit)

        # self.horizontalLayout.addWidget(self.pushButton_2)
        self.verticalLayout.addLayout(self.horizontalLayout)
        for each in self.init_groups():
            self.verticalLayout.addWidget(each)

        spacerItem1 = QtWidgets.QSpacerItem(183, 14, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem1)

        self.zbyp_textEdit = QtWidgets.QTextEdit(self)
        self.zbyp_textEdit.setPlaceholderText("1、这里将会显示预览；\n2、添加新项目会自动提取这里的内容。")
        self.verticalLayout.addWidget(self.zbyp_textEdit)
        self.verticalLayout_2.addLayout(self.verticalLayout)

    def init_groups(self):

        group_box_list = []
        self.symptom_detail = read_json("zbyp.json")
        symptom_list = read_json("zbyp_list.json")
        self.radio_button_symptom_group = radio_button_symptom_group = QtWidgets.QButtonGroup(self)
        for each in symptom_list:
            for k, v in each.items():
                group_box = QtWidgets.QGroupBox(k, self)
                symptomLayout = QtWidgets.QGridLayout()
                row = 0
                col = 0
                for each_k in v:                  
                    obj = QtWidgets.QRadioButton(each_k)
                    symptomLayout.addWidget(obj, row, col, 1, 1)
                    radio_button_symptom_group.addButton(obj)
                    col += 1
                    if col > 5:
                        col = 0
                        row += 1
                group_box.setLayout(symptomLayout)
                group_box_list.append(group_box)
        radio_button_symptom_group.buttonClicked.connect(self.submit)

        return group_box_list

    def submit(self):
        result = self.symptom_detail.get(self.radio_button_symptom_group.checkedButton().text())
        drug_bought_by_patient(self.window.info_dic, result)


    def add(self):
        json_file = {"list_file": "zbyp_list.json", "detail_file": "zbyp.json"}
        dialog = AddZbypDialog(json_file)
        dialog.setWindowModality(QtCore.Qt.ApplicationModal)
        dialog.exec_()



        btn_layout.addStretch()
        layout.addLayout(btn_layout)

        self.text_edit = QtWidgets.QTextEdit()
        # clipboard = QtWidgets.QApplication.clipboard()

        # text = clipboard.text()
        # self.text_edit.setText(text)

        self.text_edit.textChanged.connect(self.ok_func)
        self.text_edit.setPlaceholderText("请输入化验单内容或点按钮读取剪贴板内容")

        layout.addWidget(self.text_edit)

        self.text_edit_show = QtWidgets.QTextEdit()
        self.text_edit_show.setPlaceholderText("这里会显示预览...")

        layout.addWidget(self.text_edit_show)

        self.setLayout(layout)

    def read_clipboard_func(self):
        # 读取剪贴板
        clipboard = QtWidgets.QApplication.clipboard()

        text = clipboard.text()
        # 写入text
        self.text_edit.setText(text)

    def ok_func(self):
        from utils.hyd_manully import hyd_func
        texts_to_cut = self.text_edit.toPlainText()
        texts = hyd_func(texts_to_cut)
        if texts:
            clipboard = QtWidgets.QApplication.clipboard()

            clipboard.setText(texts)
        else:
            texts = f"输入格式错误，无法转换此内容：\n【{texts_to_cut}】"
        self.text_edit_show.setText(texts)


class AddDialog(QtWidgets.QDialog):
    # 添加功能
    def __init__(self, content, json_file, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.content = content
        self.json_file = json_file
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("")
        # self.resize(500, 400)
        layout = QtWidgets.QVBoxLayout()
        btn_layout = QtWidgets.QHBoxLayout()

        self.confirm = QtWidgets.QPushButton("确定")
        self.confirm.clicked.connect(self.confirm_fcn)
        btn_layout.addWidget(self.confirm)

        self.cancel = QtWidgets.QPushButton("取消")
        self.cancel.clicked.connect(self.cancel_fcn)
        btn_layout.addWidget(self.cancel)

        btn_layout.addStretch()
        layout.addLayout(btn_layout)

        layout.addWidget(QtWidgets.QLabel("请选择项目类别："))
        self.ComboBox = QtWidgets.QComboBox()
        # bcjl_list = read_json("bcjl_list.json")
        bcjl_list = read_json(self.json_file.get("list_file"))
        for each in bcjl_list:
            for key in each.keys():
                self.ComboBox.addItem(key)

        layout.addWidget(self.ComboBox)
        self.info = info = QtWidgets.QLabel("请输入项目名称：")
        layout.addWidget(info)
        self.text_edit = QtWidgets.QLineEdit()

        # self.text_edit.textChanged.connect(self.ok_func)
        self.text_edit.setPlaceholderText("请输入项目名称")

        layout.addWidget(self.text_edit)

        self.text_edit_show = QtWidgets.QTextEdit()
        self.text_edit_show.setText(self.content)
        self.text_edit_show.setPlaceholderText("请输入项目明细")

        layout.addWidget(self.text_edit_show)

        self.setLayout(layout)

    def confirm_fcn(self):
        kind = self.ComboBox.currentText()
        name = self.text_edit.text()
        content = self.text_edit_show.toPlainText()
        bcjl_list = read_json(self.json_file.get("list_file"))
        for each in bcjl_list:
            if each.get(kind):
                if name in each[kind]:
                    self.info.setText(f"名称【{name}】已存在，请重新输入！")
                    self.info.setStyleSheet("QLabel { color : red; }")
                    self.info.repaint()
                    self.text_edit.clear()
                    return
                each[kind].append(name)
        add_json(self.json_file.get("list_file"), bcjl_list)

        bcjl = read_json(self.json_file.get("detail_file"))
        bcjl[name] = content
        add_json(self.json_file.get("detail_file"), bcjl)
        self.close()

    def cancel_fcn(self):
        self.close()

class AddZbypDialog(QtWidgets.QDialog):
    # 添加自备药品功能
    def __init__(self, json_file, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.json_file = json_file
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("自备药品")
        self.resize(500, 400)
        layout = QtWidgets.QVBoxLayout()
        btn_layout = QtWidgets.QHBoxLayout()

        self.confirm = QtWidgets.QPushButton("确定")
        self.confirm.clicked.connect(self.confirm_fcn)
        btn_layout.addWidget(self.confirm)

        self.cancel = QtWidgets.QPushButton("取消")
        self.cancel.clicked.connect(self.cancel_fcn)
        btn_layout.addWidget(self.cancel)

        btn_layout.addStretch()
        layout.addLayout(btn_layout)

        layout.addWidget(QtWidgets.QLabel("请选择药品类别："))
        self.ComboBox = QtWidgets.QComboBox()
        bcjl_list = read_json(self.json_file.get("list_file"))
        for each in bcjl_list:
            for key in each.keys():
                self.ComboBox.addItem(key)

        layout.addWidget(self.ComboBox)

        self.info = info = QtWidgets.QLabel("请输入药品名称：")
        layout.addWidget(info)

        self.text_edit = QtWidgets.QLineEdit()

        self.text_edit.setPlaceholderText("请输入药品名称")

        layout.addWidget(self.text_edit)


        layout.addWidget(QtWidgets.QLabel("请输入药品规格："))
        self.text_edit_gg = QtWidgets.QLineEdit()
        self.text_edit_gg.setPlaceholderText("1.5mg")
        layout.addWidget(self.text_edit_gg)

        layout.addWidget(QtWidgets.QLabel("请输入药品批号："))
        self.text_edit_ph = QtWidgets.QLineEdit()
        self.text_edit_ph.setPlaceholderText("H10960113/2025.07")
        layout.addWidget(self.text_edit_ph)



        layout.addWidget(QtWidgets.QLabel("请输入药品厂家："))
        self.text_edit_cj = QtWidgets.QLineEdit()
        self.text_edit_cj.setPlaceholderText("辉瑞制药有限公司")
        layout.addWidget(self.text_edit_cj)

        layout.addWidget(QtWidgets.QLabel("请输入药品途径："))
        self.text_edit_tj = QtWidgets.QLineEdit()
        self.text_edit_tj.setText("外购")
        layout.addWidget(self.text_edit_tj)

        layout.addWidget(QtWidgets.QLabel("请输入药品用途："))
        self.text_edit_use = QtWidgets.QLineEdit()
        self.text_edit_use.setPlaceholderText("抗感染")
        layout.addWidget(self.text_edit_use)
        self.setLayout(layout)

    def confirm_fcn(self):
        kind = self.ComboBox.currentText()
        name = self.text_edit.text()
        gg = self.text_edit_gg.text()
        ph = self.text_edit_ph.text()
        cj = self.text_edit_cj.text()
        tj = self.text_edit_tj.text()
        use = self.text_edit_use.text()



        bcjl_list = read_json(self.json_file.get("list_file"))
        for each in bcjl_list:
            if each.get(kind):
                if name in each[kind]:
                    self.info.setText(f"名称【{name}】已存在，请重新输入！")
                    self.info.setStyleSheet("QLabel { color : red; }")
                    self.info.repaint()
                    self.text_edit.clear()
                    return
                each[kind].append(name)
        add_json(self.json_file.get("list_file"), bcjl_list)

        bcjl = read_json(self.json_file.get("detail_file"))
        bcjl[name] = {'药品名称': name, '规格': gg, '批号': ph, '数量': '', '厂家': cj, '途径': tj, '用途': use}
        add_json(self.json_file.get("detail_file"), bcjl)
        self.close()

    def cancel_fcn(self):
        self.close()

class CfDialog(QtWidgets.QDialog):
    # 主任查房
    def __init__(self, window, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.window = window  # 接收父级窗体变量
        self.setupUi()
        self.retranslateUi()

    def setupUi(self):
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.radioButton_3 = QtWidgets.QRadioButton(self)
        self.radioButton_3.setChecked(True)
        self.radioButton_3.setObjectName("radioButton_3")
        self.horizontalLayout.addWidget(self.radioButton_3)
        self.radioButton_4 = QtWidgets.QRadioButton(self)
        self.radioButton_4.setObjectName("radioButton_4")
        self.kind_group = kind_group = QtWidgets.QButtonGroup(self)
        kind_group.addButton(self.radioButton_3)
        kind_group.addButton(self.radioButton_4)
        self.horizontalLayout.addWidget(self.radioButton_4)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        # self.pushButton = QtWidgets.QPushButton(self)
        # self.horizontalLayout.addWidget(self.pushButton)
        # 确定按钮
        self.pushButton_2 = QtWidgets.QPushButton(self)
        self.pushButton_2.clicked.connect(self.submit)

        self.horizontalLayout.addWidget(self.pushButton_2)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.verticalLayout.addWidget(self.init_symptom())
        self.verticalLayout.addWidget(self.init_difdig())

        spacerItem1 = QtWidgets.QSpacerItem(183, 14, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem1)

        self.zrcf_textEdit = QtWidgets.QTextEdit(self)
        self.verticalLayout.addWidget(self.zrcf_textEdit)
        self.verticalLayout_2.addLayout(self.verticalLayout)

        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Dialog", "Dialog"))
        self.radioButton_3.setText(_translate("Dialog", "副主任查房"))
        self.radioButton_4.setText(_translate("Dialog", "主任查房"))
        # self.pushButton.setText(_translate("Dialog", "添加"))
        self.pushButton_2.setText(_translate("Dialog", "确定"))

    def init_symptom(self):
        group_box = QtWidgets.QGroupBox("症状", self)
        symptomLayout = QtWidgets.QGridLayout()
        self.symptom_detail = read_json("symptom_select.json")
        symptom_list = read_json("symptom_list.json")
        row = 0
        col = 0

        radio_button_list = []
        self.radio_button_symptom_group = radio_button_symptom_group = QtWidgets.QButtonGroup(self)

        for each in symptom_list:
            radio_button_list.append("space" if each == "space" else QtWidgets.QRadioButton(each))

        for obj in radio_button_list:
            
            if obj == "space":
                row += 1
                col = 0
                continue
            else:

                # obj.toggled.connect(self.radio_checked_fn)
                symptomLayout.addWidget(obj, row, col, 1, 1)
                radio_button_symptom_group.addButton(obj)
                col += 1
                if col > 5:
                    col = 0
                    row += 1
        group_box.setLayout(symptomLayout)
        return group_box
        # radio_button_symptom_group.buttonClicked.connect(self.radio_checked_fn)

    def init_difdig(self):
        # 鉴别诊断
        group_box = QtWidgets.QGroupBox("鉴别诊断", self)
        difdigLayout = QtWidgets.QGridLayout()
        self.difdig_detail = read_json("dif_diagnosis.json")
        difdig_list = read_json("dif_diagnosis_list.json")
        row = 0
        col = 0

        radio_button_list = []
        self.radio_button_difdig_group = radio_button_difdig_group = QtWidgets.QButtonGroup(self)

        for each in difdig_list:
            radio_button_list.append("space" if each == "space" else QtWidgets.QRadioButton(each))

        for obj in radio_button_list:
            
            if obj == "space":
                row += 1
                col = 0
                continue
            else:

                # obj.toggled.connect(self.radio_checked_fn)
                difdigLayout.addWidget(obj, row, col, 1, 1)
                radio_button_difdig_group.addButton(obj)
                col += 1
                if col > 5:
                    col = 0
                    row += 1
        group_box.setLayout(difdigLayout)
        return group_box

    def submit(self):

        kind_flag = self.kind_group.checkedButton().text()
        # 生成随机体温
        
        symptom_selected = self.symptom_detail.get(self.radio_button_symptom_group.checkedButton().text())
        if r"%s" in symptom_selected:
            rdm_body_tmp = random.randint(385,398)/10
            symptom_selected = symptom_selected % (rdm_body_tmp)
            
        difdig_name = self.radio_button_difdig_group.checkedButton().text()
        difdig_selected = "%s：%s" %(difdig_name, self.difdig_detail.get(difdig_name))
        # 分体式：需借助ditto剪贴板工具，复制两次。
        # try:
        #     result = zrcf(kind_flag, symptom_selected, difdig_selected, self.window.info_dic)
        #     # 写入text
        #     self.zrcf_textEdit.setText(result)
        #     clipboard = QtWidgets.QApplication.clipboard()
        #     if process_monitor.check_process_running("ditto.exe"):
        #         results = result.split("，查体：")
        #         pyperclip.copy(results[1])
        #         time.sleep(0.8)
        #         pyperclip.copy(results[0])
        #     else:
        #         clipboard.setText(result)
        # except Exception as e:
        #     result = f"出错：{e}"
        
        
        # 正常模式：
        try:
            result = zrcf(kind_flag, symptom_selected, difdig_selected, self.window.info_dic)
            
            clipboard = QtWidgets.QApplication.clipboard()
           
            clipboard.setText(result)
            # 写入text
            self.zrcf_textEdit.setText(result)
        except Exception as e:
            result = f"出错：{e}"



class BcDialog(QtWidgets.QDialog):
    # 病程
    def __init__(self, window, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.window = window  # 接收父级窗体变量
        self.setupUi()

    def setupUi(self):
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        # 添加 
        self.pushButton = QtWidgets.QPushButton("添加新项目", self)
        self.pushButton.clicked.connect(self.add)
        self.horizontalLayout.addWidget(self.pushButton)
        # 确定按钮
        # self.pushButton_2 = QtWidgets.QPushButton("确定", self)
        # self.pushButton_2.clicked.connect(self.submit)

        # self.horizontalLayout.addWidget(self.pushButton_2)
        self.verticalLayout.addLayout(self.horizontalLayout)
        for each in self.init_groups():
            self.verticalLayout.addWidget(each)

        spacerItem1 = QtWidgets.QSpacerItem(183, 14, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem1)

        self.zrcf_textEdit = QtWidgets.QTextEdit(self)
        self.zrcf_textEdit.setPlaceholderText("1、这里将会显示预览；\n2、添加新项目会自动提取这里的内容。")
        self.verticalLayout.addWidget(self.zrcf_textEdit)
        self.verticalLayout_2.addLayout(self.verticalLayout)

    def init_groups(self):

        group_box_list = []
        self.symptom_detail = read_json("bcjl.json")
        symptom_list = read_json("bcjl_list.json")
        self.radio_button_symptom_group = radio_button_symptom_group = QtWidgets.QButtonGroup(self)
        for each in symptom_list:
            for k, v in each.items():
                group_box = QtWidgets.QGroupBox(k, self)
                symptomLayout = QtWidgets.QGridLayout()
                symptomLayout.setContentsMargins(10,10,10,10)
                row = 0
                col = 0
                for each_k in v:
                    
                    obj = QtWidgets.QRadioButton(each_k)
                    symptomLayout.addWidget(obj, row, col, 1, 1)
                    radio_button_symptom_group.addButton(obj)
                    col += 1
                    if col > 4:
                        col = 0
                        row += 1
                group_box.setLayout(symptomLayout)
                group_box_list.append(group_box)
        radio_button_symptom_group.buttonClicked.connect(self.submit)

        return group_box_list

    def submit(self):
        # rdn = random.randint(89,99)
        # result = self.symptom_detail.get(self.radio_button_symptom_group.checkedButton().text()).format(rdn)
        result = self.symptom_detail.get(self.radio_button_symptom_group.checkedButton().text())
        
        
        # 分体式：复制2次
        # if "查体：" in result:
        #     results = result.split("查体：")
            
        #     pyperclip.copy(results[1])
        #     time.sleep(0.8)
        #     pyperclip.copy(results[0])
        # else:
        #     pyperclip.copy(result)
        # 写入text
        # self.zrcf_textEdit.setText(result)
        
        
        
        # 正常式：自动生成TPRBP 
        if "查体：" in result:
            tprbp = tools.form_TPRBP(age=self.window.info_dic['年龄'], ).rstrip(" W：")
            tprbp_list = tprbp.split()
            # 如果年龄小于8岁则不显示血压
            try:
                age_ = int(self.window.info_dic['年龄'].split('岁')[0])
                if age_ < 8:
                    tprbp = " ".join(tprbp_list[:-1])
            except Exception as e:
                # 带几岁几月或者几月几天的int函数会出错，表示也小于8岁
                tprbp = " ".join(tprbp_list[:-1])
            result = result.replace("查体：", f"查体：{tprbp} ")
            
            
        result = result.strip("\n")
        pyperclip.copy(result)
        
        # 写入text
        self.zrcf_textEdit.setText(result)


        

    def add(self):
        json_file = {"list_file": "bcjl_list.json", "detail_file": "bcjl.json"}
        dialog = AddDialog(self.zrcf_textEdit.toPlainText(), json_file)
        dialog.setWindowModality(QtCore.Qt.ApplicationModal)
        dialog.exec_()


class CmcDialog(QtWidgets.QDialog):
    # 沟通
    def __init__(self, window, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.window = window  # 接收父级窗体变量
        self.setupUi()

    def setupUi(self):
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        # spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        # self.horizontalLayout.addItem(spacerItem)
        self.radio_button_difdig_group = radio_button_difdig_group = QtWidgets.QButtonGroup()
        self.cmc1 = QtWidgets.QRadioButton("首次沟通", self)
        # self.cmc1.setChecked(True)
        # self.cmc1.toggled.connect(self.cmc_fnc)
        radio_button_difdig_group.addButton(self.cmc1)
        self.horizontalLayout.addWidget(self.cmc1)

        self.cmc_out = QtWidgets.QRadioButton("出院沟通", self)
        # self.cmc_out.toggled.connect(self.cmc_fnc)
        self.horizontalLayout.addWidget(self.cmc_out)
        radio_button_difdig_group.addButton(self.cmc_out)
        self.cmc_oral = QtWidgets.QRadioButton("普通沟通", self)
        # self.cmc_oral.toggled.connect(self.cmc_fnc)
        self.horizontalLayout.addWidget(self.cmc_oral)
        radio_button_difdig_group.addButton(self.cmc_oral)
        radio_button_difdig_group.buttonClicked.connect(self.cmc_fnc)

        self.dateTimeEdit = QtWidgets.QDateTimeEdit(QtCore.QDateTime.currentDateTime(), self)
        self.dateTimeEdit.setDisplayFormat("yyyy.MM.dd HH:mm")
        self.dateTimeEdit.setCalendarPopup(True)
        self.horizontalLayout.addWidget(self.dateTimeEdit)
        # 确定按钮
        self.pushButton_2 = QtWidgets.QPushButton("确定", self)
        self.pushButton_2.clicked.connect(self.submit)

        self.horizontalLayout.addWidget(self.pushButton_2)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.zrcf_textEdit = QtWidgets.QTextEdit(self)
        self.zrcf_textEdit.setPlaceholderText("请输入沟通内容")
        self.verticalLayout.addWidget(self.zrcf_textEdit)
        self.verticalLayout_2.addLayout(self.verticalLayout)

    def submit(self):
        dtime = self.dateTimeEdit.dateTime().toString("yyyy.MM.dd hh:mm")
        content = self.zrcf_textEdit.toPlainText()
        kind = self.radio_button_difdig_group.checkedButton()
        if not kind:
            return
        kind = kind.text()
        cmc_content(self.window.info_dic, kind=kind, fill={'时间': dtime, '内容': content})

    def cmc_fnc(self):

        kind = self.radio_button_difdig_group.checkedButton().text()
        if kind == "普通沟通": return

        msgBox = QtWidgets.QMessageBox()
        msgBox.setWindowTitle('提示')
        msgBox.setIcon(QtWidgets.QMessageBox.Warning)
        msgBox.setText(f"正在生成{kind}")
        # msgBox.setInformativeText('出现更改愿意保存吗?')
        # Save = msgBox.addButton('好的', QtWidgets.QMessageBox.AcceptRole)

        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)

        msgBox.button(QtWidgets.QMessageBox.Ok).animateClick(100)
        msgBox.exec_()
        cmc_content(self.window.info_dic, kind=kind, )


class ZyhzDialog(QtWidgets.QDialog):
    # 中医会诊
    def __init__(self, window, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.window = window  # 接收父级窗体变量
        self.setupUi()

    def setupUi(self):
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.horizontalLayout = QtWidgets.QHBoxLayout()

        # 会诊时间
        self.dateEdit = QtWidgets.QDateEdit(QtCore.QDate.currentDate(), self)
        self.dateEdit.setDisplayFormat("yyyy.MM.dd")
        self.dateEdit.setCalendarPopup(True)
        self.horizontalLayout.addWidget(self.dateEdit)
        self.timeEdit = QtWidgets.QTimeEdit(QtCore.QTime(9, 0), self)
        self.timeEdit.setDisplayFormat("HH:mm")
        self.timeEdit.setCalendarPopup(True)
        self.horizontalLayout.addWidget(self.timeEdit)

        # 确定按钮
        self.bs_btn = QtWidgets.QPushButton("原病史")
        self.bs_btn.clicked.connect(self.aqur_bs)
        self.horizontalLayout.addWidget(self.bs_btn)

        self.copy_btn = QtWidgets.QPushButton("复制")
        self.copy_btn.clicked.connect(self.copy_it)
        self.horizontalLayout.addWidget(self.copy_btn)

        self.pushButton_2 = QtWidgets.QPushButton("打印", self)
        self.pushButton_2.clicked.connect(self.print_it)

        self.horizontalLayout.addWidget(self.pushButton_2)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        # 添加 
        self.pushButton = QtWidgets.QPushButton("添加新项目", self)
        self.pushButton.clicked.connect(self.add)
        self.horizontalLayout.addWidget(self.pushButton)
        
        self.verticalLayout.addLayout(self.horizontalLayout)
        # 会诊医师
        self.hLayout = QtWidgets.QHBoxLayout()
        self.lable = QtWidgets.QLabel("会诊医师：")
        self.hLayout.addWidget(self.lable)
        
        self.name = QtWidgets.QLineEdit()
        self.name.setPlaceholderText("输入医师姓名加职称")
        self.hLayout.addWidget(self.name)
        self.verticalLayout.addLayout(self.hLayout)
        # 选项
        
        for each in self.init_groups():
            self.verticalLayout.addWidget(each)

        # spacerItem1 = QtWidgets.QSpacerItem(183, 14, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        # self.verticalLayout.addItem(spacerItem1)
        # 文本框
        # 病史

        self.bs_textEdit = QtWidgets.QTextEdit(self)
        self.bs_textEdit.setPlaceholderText("这里将会显示病史")
        thread = FreshInfoThread(self.window, self)
        # 成功信号的时候需要做的事，
        thread.success.connect(self.aqur_bs)
        thread.start()
        self.verticalLayout.addWidget(self.bs_textEdit)
        # 总结
        self.hlt = QtWidgets.QHBoxLayout()
        self.zj_textEdit = QtWidgets.QTextEdit(self)
        self.zj_textEdit.setPlaceholderText("这里将会显示总结")
        self.hlt.addWidget(self.zj_textEdit)
        # 意见
        self.yj_textEdit = QtWidgets.QTextEdit(self)
        self.yj_textEdit.setPlaceholderText("这里将会显示意见")
        self.hlt.addWidget(self.yj_textEdit)
        self.verticalLayout.addLayout(self.hlt)
        self.verticalLayout_2.addLayout(self.verticalLayout)

    def aqur_bs(self, i):
        bs = f'{self.window.info_dic.get("姓名")}，{self.window.info_dic.get("性别")}，{self.window.info_dic.get("年龄")}，以“{self.window.info_dic.get("主诉")}”为代主诉入院 查体：{self.window.info_dic.get("入院体检")}'
        self.bs_textEdit.setText(bs)

    def init_groups(self):

        group_box_list = []
        self.symptom_detail = read_json("zyhz.json")
        symptom_list = read_json("zyhz_list.json")
        self.radio_button_symptom_group = radio_button_symptom_group = QtWidgets.QButtonGroup(self)
        for each in symptom_list:
            for k, v in each.items():
                group_box = QtWidgets.QGroupBox(k, self)
                symptomLayout = QtWidgets.QGridLayout()
                row = 0
                col = 0
                for each_k in v:

                    obj = QtWidgets.QRadioButton(each_k)
                    symptomLayout.addWidget(obj, row, col, 1, 1)
                    radio_button_symptom_group.addButton(obj)
                    col += 1
                    if col > 4:
                        col = 0
                        row += 1
                group_box.setLayout(symptomLayout)
                group_box_list.append(group_box)
        radio_button_symptom_group.buttonClicked.connect(self.submit)

        return group_box_list

    def submit(self):
        
        chosen = self.symptom_detail.get(self.radio_button_symptom_group.checkedButton().text())
        zj, yj = chosen.split("zyhz")
        date_ = self.dateEdit.date()
        time_1 = self.timeEdit.time()
        time_2 = time_1.addSecs(30 * 60)
        start_time = date_.toString("yyyy年MM月dd日") + " " + time_1.toString("HH:mm")
        arrivel_time = date_.toString("yyyy年MM月dd日") + " " + time_2.toString("HH:mm")
        # 写入text

        self.zj_textEdit.setText(zj)
        self.yj_textEdit.setText(yj)
        # result = '患者姓名：{}，性别：{}，年龄：{}。目前诊断：{} 申请会诊目的：辨证施治，会诊申请时间：{}，请中医儿科赵峥主任医师会诊，会诊医师到达时间：{}。会诊简要经过：赵峥主任医师床旁查看患儿、详细询问病史并做体格检查。{}{} 会诊意见执行情况：已执行。'.format(
        #     self.window.info_dic.get("姓名"),
        #     self.window.info_dic.get("性别"),
        #     self.window.info_dic.get("年龄"),
        #     self.window.info_dic.get("诊断"),
        #     start_time, arrivel_time,
        #     zj, yj
        # )
        result = '申请会诊目的：辨证施治，会诊申请时间：{}，请中医儿科赵峥主任医师会诊，会诊医师到达时间：{}。会诊简要经过：赵峥主任医师床旁查看患儿、详细询问病史并做体格检查。{}{} 会诊意见执行情况：已执行。'.format(
            
            start_time, arrivel_time,
            zj, yj
        )
        clipboard = QtWidgets.QApplication.clipboard()

        clipboard.setText(result)

    def copy_it(self):
        date_ = self.dateEdit.date()
        time_1 = self.timeEdit.time()
        time_2 = time_1.addSecs(30 * 60)
        start_time = date_.toString("yyyy年MM月dd日") + " " + time_1.toString("HH:mm")
        arrivel_time = date_.toString("yyyy年MM月dd日") + " " + time_2.toString("HH:mm")
        
        zj = self.zj_textEdit.toPlainText()
        yj = self.yj_textEdit.toPlainText()
        # result = '患者姓名：{}，性别：{}，年龄：{}。目前诊断：{} 申请会诊目的：辨证施治，会诊申请时间：{}，请中医儿科赵峥主任医师会诊，会诊医师到达时间：{}。会诊简要经过：赵峥主任医师床旁查看患儿、详细询问病史并做体格检查。{}{} 会诊意见执行情况：已执行。'.format(
        #     self.window.info_dic.get("姓名"),
        #     self.window.info_dic.get("性别"),
        #     self.window.info_dic.get("年龄"),
        #     self.window.info_dic.get("诊断"),
        #     start_time, arrivel_time,
        #     zj, yj
        # )
        result = '申请会诊目的：辨证施治，会诊申请时间：{}，请中医儿科赵峥主任医师会诊，会诊医师到达时间：{}。会诊简要经过：赵峥主任医师床旁查看患儿、详细询问病史并做体格检查。{}{} 会诊意见执行情况：已执行。'.format(
            
           
            start_time, arrivel_time,
            zj, yj
        )
        clipboard = QtWidgets.QApplication.clipboard()

        clipboard.setText(result)
    def print_it(self):
        text_info = self.window.info_dic
        date_ = self.dateEdit.date()
        time_1 = self.timeEdit.time()
        time_2 = time_1.addSecs(30 * 60)
        start_time = date_.toString("yyyy年MM月dd日") + " " + time_1.toString("HH:mm")
        arrivel_time = date_.toString("yyyy年MM月dd日") + " " + time_2.toString("HH:mm")
        date_dic = {
            "start_time": start_time,
            "arrivel_time": arrivel_time,
        }
        bs = self.bs_textEdit.toPlainText()
        if not bs:
            QtWidgets.QMessageBox.critical(self, "错误！", "病史不能为空！")
            return
        zj = self.zj_textEdit.toPlainText()
        yj = self.yj_textEdit.toPlainText()
        consult_content = {
            '病史': bs,
            '总结': zj,
            '意见': yj
        }
        zyhz_fill_word(text_info, date_dic, consult_content)

    def add(self):
        json_file = {"list_file": "zyhz_list.json", "detail_file": "zyhz.json"}
        content = "{}zyhz{}".format(self.zj_textEdit.toPlainText(), self.yj_textEdit.toPlainText())
        dialog = AddDialog(content, json_file)
        dialog.setWindowModality(QtCore.Qt.ApplicationModal)
        dialog.exec_()


class ZbypDialog(QtWidgets.QDialog):
    # 自备药品
    def __init__(self, window, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.window = window  # 接收父级窗体变量
        self.setupUi()

    def setupUi(self):
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        # 添加
        self.pushButton = QtWidgets.QPushButton("添加新项目", self)
        self.pushButton.clicked.connect(self.add)
        self.horizontalLayout.addWidget(self.pushButton)
        # 确定按钮
        # self.pushButton_2 = QtWidgets.QPushButton("确定", self)
        # self.pushButton_2.clicked.connect(self.submit)

        # self.horizontalLayout.addWidget(self.pushButton_2)
        self.verticalLayout.addLayout(self.horizontalLayout)
        for each in self.init_groups():
            self.verticalLayout.addWidget(each)

        spacerItem1 = QtWidgets.QSpacerItem(183, 14, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem1)

        self.zbyp_textEdit = QtWidgets.QTextEdit(self)
        self.zbyp_textEdit.setPlaceholderText("1、这里将会显示预览；\n2、添加新项目会自动提取这里的内容。")
        self.verticalLayout.addWidget(self.zbyp_textEdit)
        self.verticalLayout_2.addLayout(self.verticalLayout)

    def init_groups(self):

        group_box_list = []
        self.symptom_detail = read_json("zbyp.json")
        symptom_list = read_json("zbyp_list.json")
        self.radio_button_symptom_group = radio_button_symptom_group = QtWidgets.QButtonGroup(self)
        for each in symptom_list:
            for k, v in each.items():
                group_box = QtWidgets.QGroupBox(k, self)
                symptomLayout = QtWidgets.QGridLayout()
                row = 0
                col = 0
                for each_k in v:                  
                    obj = QtWidgets.QRadioButton(each_k)
                    symptomLayout.addWidget(obj, row, col, 1, 1)
                    radio_button_symptom_group.addButton(obj)
                    col += 1
                    if col > 5:
                        col = 0
                        row += 1
                group_box.setLayout(symptomLayout)
                group_box_list.append(group_box)
        radio_button_symptom_group.buttonClicked.connect(self.submit)

        return group_box_list

    def submit(self):
        result = self.symptom_detail.get(self.radio_button_symptom_group.checkedButton().text())
        drug_bought_by_patient(self.window.info_dic, result)


    def add(self):
        json_file = {"list_file": "zbyp_list.json", "detail_file": "zbyp.json"}
        dialog = AddZbypDialog(json_file)
        dialog.setWindowModality(QtCore.Qt.ApplicationModal)
        dialog.exec_()


class InfoDialog(QtWidgets.QDialog):
    def __init__(self, pid, row, title, window, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
        self.pid = pid
        self.row = row
        self.window = window
        
        self.title = title
        self.info_dic = {}
        self.init_data_local()
        self.setupUi()
        self.retranslateUi()
        self.setWindowTitle(self.title)
        self.setWindowIcon(QIcon("dialog.png"))

    def init_data_local(self):
        thread = InfoThread(self.pid, self)
        # 成功信号的时候需要做的事，
        thread.success.connect(self.info_success_callback)
        thread.start()

    def init_data_network(self):
        # 刷新数据
        self.update_status_msg(f"正在更新【{self.pid}】...")
        start_date_given = self.info_dic.get("入院时间")
        end_date_given=self.info_dic.get("出院日期")
        if start_date_given:
            start_date_given = start_date_given.split()[0]
        if end_date_given in ["None", "无信息"]:
            end_date_given=None
            
            
        thread = RenewThread(self.pid, self.row, start_date_given,end_date_given,self)
        # 成功信号的时候需要做的事，
        thread.success.connect(self.info_renew_success_callback)
        thread.error.connect(self.info_renew_error_callback)
        thread.start()

    def info_renew_success_callback(self, index, result_dic):
        model = self.window.model
        self.window.model.select()

        self.window.table_view.setModel(model)

        # 更新弹窗
        self.info_dic = result_dic
        self.info_success_callback(result_dic)

        # 生成tab页面

        self.update_status_msg(f"【{self.pid}】信息已更新。")

    def info_renew_error_callback(self, error):
        QtWidgets.QMessageBox.critical(self, "错误！", error)
        self.update_status_msg(f"更新失败：{error}")

    def info_success_callback(self, info_dic, info=None):
        total_rows = self.tableWidget.rowCount()
        for _i in range(total_rows):
            self.tableWidget.removeRow(0)
           
        self.info_dic = info_dic
        # current_row_count = self.tableWidget.rowCount()
        current_row_count = 0
        keywords_list = keyword()

        for key in keywords_list:

            # 添加一行

            self.tableWidget.insertRow(current_row_count)
            for ix, element in enumerate([key, info_dic.get(key)]):
                cell = QtWidgets.QTableWidgetItem(str(element))

                self.tableWidget.setItem(current_row_count, ix, cell)
            current_row_count += 1
        self.tableWidget.itemChanged.connect(self.update_data)
        if not info:
            self.update_status_msg(f"{info}")
    def setupUi(self):
        self.setObjectName("Dialog")
        self.resize(1060, 744)
        self.widget = QtWidgets.QWidget(self)
        self.widget.setGeometry(QtCore.QRect(10, 30, 971, 691))
        self.widget.setObjectName("widget")
        self.label_status = QtWidgets.QLabel(self.widget)

        info_layout = QtWidgets.QVBoxLayout(self.widget)

        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.tableWidget = QtWidgets.QTableWidget(self.widget)

        self.tableWidget.setColumnCount(2)
        table_header = [
            {"field": "name", "text": "项目", "width": 65},
            {"field": "content", "text": "明细", "width": 120},

        ]
        for idx, info in enumerate(table_header):
            item = QtWidgets.QTableWidgetItem()
            item.setText(info["text"])
            self.tableWidget.setHorizontalHeaderItem(idx, item)
            self.tableWidget.setColumnWidth(idx, info["width"])

        self.tableWidget.setObjectName("tableWidget")
        
        #self.tableWidget.itemClicked.connect(self.copy_info)
        self.horizontalLayout.addWidget(self.tableWidget)

        self.tabWidget = QtWidgets.QTabWidget(self.widget)
        self.tabWidget.setObjectName("tabWidget")

        self.tab_7 = QtWidgets.QWidget()
        self.tab_7.setObjectName("tab_7")
        self.widget1 = QtWidgets.QWidget(self.tab_7)
        self.widget1.setGeometry(QtCore.QRect(70, 60, 491, 121))
        self.widget1.setObjectName("widget1")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.widget1)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        # 诊断证明
        self.pushButton_3 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.clicked.connect(self.dio_report_fn)

        self.horizontalLayout_2.addWidget(self.pushButton_3)
        self.pushButton_2 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.yb_fn)
        self.horizontalLayout_2.addWidget(self.pushButton_2)

        self.pushButton_5 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_5.clicked.connect(self.na_fn)
        self.horizontalLayout_2.addWidget(self.pushButton_5)

        self.pushButton_4 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_4.clicked.connect(self.auto_homepage)
        self.horizontalLayout_2.addWidget(self.pushButton_4)
        # 刷新按钮
        self.pushButton_11 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_11.setStyleSheet("background-color: rgb(250,128,114)")
        self.pushButton_11.setObjectName("pushButton_11")
        self.pushButton_11.clicked.connect(self.init_data_network)

        self.horizontalLayout_2.addWidget(self.pushButton_11)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        
        self.pushButton_6 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_6.clicked.connect(self.patient_info_record)
        self.pushButton_6.setObjectName("pushButton_6")
        self.horizontalLayout_3.addWidget(self.pushButton_6)
        
        self.pushButton_12 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_12.clicked.connect(self.in_input_id)
        self.pushButton_12.setObjectName("pushButton_12")
        self.horizontalLayout_3.addWidget(self.pushButton_12)
        
        self.pushButton_10 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_10.clicked.connect(self.in_input)
        self.pushButton_10.setObjectName("pushButton_10")
        self.horizontalLayout_3.addWidget(self.pushButton_10)
        
 
        
        
        self.pushButton = QtWidgets.QPushButton(self.widget1)
        self.pushButton.clicked.connect(self.out_input)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_3.addWidget(self.pushButton)
        
        self.pushButton_8 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_8.clicked.connect(self.shot_cmn)
        self.pushButton_8.setObjectName("pushButton_8")

        self.horizontalLayout_3.addWidget(self.pushButton_8)
        
        self.pushButton_9 = QtWidgets.QPushButton(self.widget1)
        self.pushButton_9.clicked.connect(self.admission_card)
        self.pushButton_9.setObjectName("pushButton_9")
        self.horizontalLayout_3.addWidget(self.pushButton_9)   
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        
        # 第三行按钮
        self.horizontalLayout_rd = QtWidgets.QHBoxLayout()
        self.horizontalLayout_rd.setObjectName("horizontalLayout_rd")
        # 诊断证明
        self.pushButton_brief = QtWidgets.QPushButton(self.widget1)
        self.pushButton_brief.setObjectName("pushButton_brief")
        self.pushButton_brief.clicked.connect(self.patient_brief)

        self.horizontalLayout_rd.addWidget(self.pushButton_brief)
        self.verticalLayout.addLayout(self.horizontalLayout_rd)
        
        
        self.tabWidget.addTab(self.tab_7, "")

        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.tabWidget.addTab(self.tab, "")

        # self.tab_2 = QtWidgets.QWidget()
        # self.tab_2.setObjectName("tab_2")
        # self.tabWidget.addTab(self.tab_2, "")

        self.tab_3 = QtWidgets.QWidget()
        self.tab_3.setObjectName("tab_3")
        self.tabWidget.addTab(self.tab_3, "")

        self.tab_4 = QtWidgets.QWidget()
        self.tab_4.setObjectName("tab_4")
        self.tabWidget.addTab(self.tab_4, "")

        self.tab_5 = QtWidgets.QWidget()
        self.tab_5.setObjectName("tab_5")
        self.tabWidget.addTab(self.tab_5, "")

        self.tab_6 = QtWidgets.QWidget()
        self.tab_6.setObjectName("tab_6")
        self.tabWidget.addTab(self.tab_6, "")
        self.tab_8 = QtWidgets.QWidget()
        self.tab_8.setObjectName("tab_8")
        self.tabWidget.addTab(self.tab_8, "")

        self.horizontalLayout.addWidget(self.tabWidget)
        self.horizontalLayout.setStretch(0, 2)
        self.horizontalLayout.setStretch(1, 4)

        self.retranslateUi()
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(self)
        info_layout.addLayout(self.horizontalLayout)
        info_layout.addWidget(self.label_status)
        self.init_tab()

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Dialog", "Dialog"))
        self.pushButton_3.setText(_translate("Dialog", "诊断证明"))
        self.pushButton_2.setText(_translate("Dialog", "医保"))
        self.pushButton_5.setText(_translate("Dialog", "营养评估"))
        self.pushButton_4.setText(_translate("Dialog", "自动首页"))
        self.pushButton_11.setText(_translate("Dialog", "刷新！"))
        self.pushButton_8.setText(_translate("Dialog", "沟通"))
        self.pushButton_9.setText(_translate("Dialog", "入院证"))
        self.pushButton_10.setText(_translate("Dialog", "入院录入"))
        self.pushButton_12.setText(_translate("Dialog", "ID录入"))
        self.pushButton.setText(_translate("Dialog", "出院录入"))
        self.pushButton_6.setText(_translate("Dialog", "病人信息"))
        self.pushButton_brief.setText(_translate("Dialog", "病情简介"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_7), _translate("Dialog", "病人信息"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_8), _translate("Dialog", "输入化验单"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Dialog", "主任查房"))
        # self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Dialog", "主任"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("Dialog", "病程"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("Dialog", "沟通"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), _translate("Dialog", "中医会诊"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_6), _translate("Dialog", "自备药品"))
        self.tabWidget.currentChanged['int'].connect(self.tab_index_fun)  # 绑定标签点击时的信号与槽函数

    def tab_index_fun(self, idx):

        if idx == 1:
            pass

    # 每个tab定制页面
    def init_tab(self):
        # 输入化验单
        layout_hyd = QtWidgets.QVBoxLayout()
        ui_hyd = HydDialog()
        layout_hyd.addWidget(ui_hyd)
        self.tab_8.setLayout(layout_hyd)
        # 主任查房
        layout_cf = QtWidgets.QVBoxLayout()
        ui_cf = CfDialog(self)
        layout_cf.addWidget(ui_cf)
        self.tab.setLayout(layout_cf)
        # 病程
        layout_bc = QtWidgets.QVBoxLayout()
        ui_bc = BcDialog(self)
        layout_bc.addWidget(ui_bc)
        self.tab_3.setLayout(layout_bc)

        # 沟通
        layout_cmc = QtWidgets.QVBoxLayout()
        ui_cmc = CmcDialog(self)
        layout_cmc.addWidget(ui_cmc)
        self.tab_4.setLayout(layout_cmc)
        # 中医会诊
        layout_zyhz = QtWidgets.QVBoxLayout()
        ui_zyhz = ZyhzDialog(self)
        layout_zyhz.addWidget(ui_zyhz)
        self.tab_5.setLayout(layout_zyhz)

        # 自备药品
        layout_zbyp = QtWidgets.QVBoxLayout()
        ui_zbyp = ZbypDialog(self)
        layout_zbyp.addWidget(ui_zbyp)
        self.tab_6.setLayout(layout_zbyp)

    def copy_info(self, item=None):
        if item is None:
            return
        else:
            row = item.row()
            # col = item.column()
            name = self.tableWidget.item(row, 0).text().strip()
            info = self.tableWidget.item(row, 1).text().strip()
            clipboard = QtWidgets.QApplication.clipboard()
            clipboard.setText(info)
            self.update_status_msg(f"已复制：【{name}】->{info}")
    def update_data(self, item):
        
        if item:
            row = item.row()
            key = self.tableWidget.item(row, 0).text().strip()
            val = item.text().strip()
            
            if key == "床号" and val.isnumeric():
                ward_bed = read_json("ward_bed.json")
                for each in ward_bed:
                    
                    if str(int(val)) in each['bed']:
                        val = str(int(each['ward'])*100+int(val))
                        val = str(val).rjust(4, "0")
                        cell = QtWidgets.QTableWidgetItem(val)
                        self.tableWidget.setItem(row, 1, cell)
                        break
                        
            self.info_dic[key]=val
            thread = UpdateThread(self.pid, self.info_dic, self)
            # 成功信号的时候需要做的事，
            # thread.success.connect(self.info_success_callback)
            # thread.error.connect(self.info_renew_error_callback)
            thread.start()
    
    def patient_brief(self):
        d1 = self.info_dic.get('病例特点', '').strip("\n")
        d2 = self.info_dic.get('入院体检', '').strip("\n")
        content = f"{d1} 查体：{d2}"
        clipboard = QtWidgets.QApplication.clipboard()
        clipboard.setText(content)
        self.update_status_msg(f"【{self.info_dic.get('姓名', '')}】病情简介（出院记录用）内容已复制到剪贴板。")
            
    def update_status_msg(self, msg):

        self.label_status.setText(msg)
        self.label_status.repaint()

    def auto_homepage(self):
        # TODO:首页自动化
        self.setWindowState(QtCore.Qt.WindowMinimized)

    def dio_report_fn(self):
        # 诊断证明
        dio_report(self.info_dic)

    def yb_fn(self):
        # 打印医保
        clipboard = QtWidgets.QApplication.clipboard()
        clipboard.setText(self.info_dic.get('住院号'))
        print_file('.\\mydocx\\bcnotification.docx')

    def na_fn(self):
        # 营养评估
        nutritional_evaluation(self.info_dic)

    def admission_card(self):
        # 入院证
        gen_admisson_card(self.info_dic)
        

        
        
    def in_shotcut(self):
        # 营养评估
        nutritional_evaluation(self.info_dic)
        # 首次沟通
        cmc_content(self.info_dic, kind="首次沟通", )

    def shot_cmn(self):
        # 沟通

        zljh = re.sub(r"请陈志鑫中医主治医师.+?治疗。", '', self.info_dic.setdefault('诊疗计划', '无信息')) if self.info_dic.setdefault('诊疗计划',
                                                                                                               '') else "无信息"
        zljh = re.sub(r"压缩雾化吸入使雾化.+?疗效。", '', zljh)                                                                                                       
        
        d1 = f"患儿目前病情状况：{self.info_dic.get('病例特点', '')}可能进一步加重，亦可累及其他脏器，合并心肌损伤、肝损伤等多脏器损害，甚至呼吸循环衰竭等危及生命情况。"

        d2 = f"初步治疗计划：{zljh} {self.info_dic.get('拟行检查', '')}"
        d3 = "在治疗过程中、后可能发生的、不可避免的不良反应及副作用：由于医学尚有许多未确定因素，疾病的发生、发展也因个体差异存在许多意外情况，在检查治疗过程中可能会出现：1.治疗效果差甚至无效；2.发生药物过敏反应、输液反应等；3.身体本身疾病加重或潜在并发症、伴发疾病发作致病情加重；4.其他不可预计的情形等情况。疾病进一步加重导致多脏器功能衰竭，严重时危及生命。"
        d4 = "病情预后：大部分患儿经治疗后症状缓解，各项指标逐渐恢复正常，小部分患儿可能出现反复发热、代谢紊乱、继发感染、甚至多脏器损害等。"
        d5 = "医师需要告知患者和患者及家属需要了解的其他情况：1）遵守医院病房管理各项规定，配合护士保持病房清洁、通风，按时缴纳住院费用，病情变化及时与主管医师或值班医师沟通。2）参加城乡居民医保患者3日内需要家长带身份证或户口本和农合证（医保卡）等有效身份证件找主管医师审核身份，办理医保登记。"
        content = f"{d1}\n{d2}\n{d3}\n{d4}\n{d5}"
        clipboard = QtWidgets.QApplication.clipboard()
        clipboard.setText(content)
        self.update_status_msg(f"【{self.info_dic.get('姓名', '')}】沟通内容已复制到剪贴板。")
    def out_shotcut(self):
        # 打印医保
        clipboard = QtWidgets.QApplication.clipboard()
        clipboard.setText(self.info_dic.get('住院号'))
        print_file('.\\mydocx\\bcnotification.docx')

        # 出院沟通
        cmc_content(self.info_dic, kind="出院沟通", )
        
        
    def in_input(self):
        info = update_patient_info_in("")
        self.info_dic.update(info)
        thread = UpdateThread(self.pid, self.info_dic, self)
        thread.success.connect(self.info_success_callback)
           
        thread.start()
            
    def patient_info_record(self):
        info = update_patient_info("")
        self.info_dic.update(info)
        thread = UpdateThread(self.pid, self.info_dic, self)
        thread.success.connect(self.info_success_callback)
           
        thread.start()
    
    def in_input_id(self):
        info = update_patient_info_id("")
        self.info_dic.update(info)
        thread = UpdateThread(self.pid, self.info_dic, self)
        thread.success.connect(self.info_success_callback)
           
        thread.start()
        
    def out_input(self):
        info = update_patient_info_out("")
        self.info_dic.update(info)
        thread = UpdateThread(self.pid, self.info_dic, self)
        thread.success.connect(self.info_success_callback)
        thread.start()